import { getTokenAsync } from './secure-storage';
import { API_BASE_URL, SRS_API_HOST, SRS_HTTP_HOST, SRS_WEBRTC_PORT } from '@/config/env';

export interface WebRtcTokenResponse {
  code: number;
  server: string;
  sdp?: string;
  sessionid?: string;
}

/**
 * 获取 WebRTC token（推流或拉流）
 * @param stream 流名称（通常是用户ID或房间ID）
 * @param publish 是否为推流，默认为 false（拉流）
 */
export const getWebRtcToken = async (
  stream: string,
  publish: boolean = false
): Promise<WebRtcTokenResponse> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('请先登录');
  }

  const endpoint = publish ? '/api/webrtc/publish' : '/api/webrtc/play';
  const url = new URL(`${API_BASE_URL}${endpoint}`);
  url.searchParams.set('stream', stream);

  const response = await fetch(url.toString(), {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取 WebRTC token 失败' }));
    throw new Error(error.message || '获取 WebRTC token 失败');
  }

  return response.json();
};

/**
 * 获取 WebRTC 推流 token
 */
export const getWebRtcPublishToken = async (stream: string): Promise<WebRtcTokenResponse> => {
  return getWebRtcToken(stream, true);
};

/**
 * 获取 WebRTC 拉流 token
 */
export const getWebRtcPlayToken = async (stream: string): Promise<WebRtcTokenResponse> => {
  return getWebRtcToken(stream, false);
};

/**
 * 构建 WebRTC SRS 服务器地址
 */
export const getSrsWebRtcUrl = (stream: string, app: string = 'live'): string => {
  const host = SRS_HTTP_HOST.replace(/^https?:\/\//, '').split(':')[0];
  return `webrtc://${host}:${SRS_WEBRTC_PORT}/${app}/${stream}`;
};

